<template>
    <div class="home-control">
        <div class="home-bg" v-show="!isfullScren"></div>
        <div id="quarkgisContainer"></div>
        <my-header class="my-header"/>
        <my-footer class="my-footer"/>
        <div class="home-left" v-show="!isfullScren">
            <situation-water-supply class="situation-water-supply"/>
            <revenue-statistics class="revenue-statistics"/>
            <production-poor class="production-poor"/>
        </div>
        <div class="home-right" v-show="!isfullScren">
            <website-monitoring class="website-monitoring" type="flow"/>
            <website-monitoring class="website-monitoring" type="pressure"/>
            <website-monitoring class="website-monitoring" type="water"/>
            <website-monitoring class="website-monitoring" type="level"/>
            <!--            <water-monitoring class="water-monitoring"/>-->
            <!--            <equipment-monitoring class="equipment-monitoring"/>-->
        </div>
        <div id="map" style="width: 100vw; height: 100vh"></div>
        <el-button class="btn" type="primary" size="medium" @click.stop="isfullScren = !isfullScren">
            {{ isfullScren ? '显示数据' : '全屏显示' }}
        </el-button>
    </div>
</template>

<script>
import * as CommonQuarkGis from "./utils/CommonQuarkGis";
import * as Popup from "./utils/tool/Popup/Popup";
import * as QuarkGIS from "quarkgis";
import "quarkgis/Source/Widgets/widgets.css";
import {DataCenter} from "../datastore/DataCenter";
import {ThirdMent} from "../datastore/ThirdMent";
import MyHeader from "@/pages/home/MyHeader";
import MyFooter from "@/pages/home/MyFooter";
import SituationWaterSupply from "@/pages/home/SituationWaterSupply.vue";
import RevenueStatistics from "@/pages/home/RevenueStatistics.vue";
import ProductionPoor from "@/pages/home/ProductionPoor.vue";
import WebsiteMonitoring from "@/pages/home/WebsiteMonitoring.vue";
import Icon from '../assets/images/ic_marker.png';
// import EquipmentMonitoring from "@/pages/home/EquipmentMonitoring.vue";
// import WaterMonitoring from "@/pages/home/WaterMonitoring.vue";

var viewer = "";
export default {
    name: "MainControl",
    components: {
        MyHeader,
        MyFooter,
        SituationWaterSupply,
        RevenueStatistics,
        ProductionPoor,
        WebsiteMonitoring,
        // EquipmentMonitoring,
        // WaterMonitoring,
    },
    data() {
        return {
            BMap: '',
            mentList: [],
            geoJsonUrl: '',
            showPointType: "0", //0-不显示 1-阀门 2-水表 3-消防栓
            isfullScren: false
        };
    },
    mounted() {
        var that = this;
        // viewer = CommonQuarkGis.creatCommonViewer("quarkgisContainer");
        // Popup.initPopup(viewer); // 实例化状态popup框
        // that.initGeoJson(); // 加载geojson数据
        // let domain = window.location.hostname;
        // if (domain.indexOf('hubeishuiwu') >= 0) {
        //     that.initBaiduConfig();//初始化百度地图
        // } else {
        that.initMap();//初始化地图
        // }
        that.initHandle(); // 初始化鼠标点击事件
        that.initGetMentList();// 获取所有的阀门 水表 消防栓
    },
    methods: {
        /**
         * 初始化数据中心登录
         */
        initLoginDataCenter(callback) {
            var that = this;
            if (localStorage.getItem('user_key')) {
                callback();
            } else {
                var params = {
                    "name": process.env.VUE_APP_DATA_CENTER_USER_NAME,
                    "password": process.env.VUE_APP_DATA_CENTER_USER_PASSWORD
                };
                new DataCenter(this).doLogin(params, (res) => {
                    localStorage.setItem('user_key', res.data.user_key)
                    callback();
                })
            }
        },
        initGetMentList() {
            var that = this;
            var apiParams = {};
            new ThirdMent(this).getMentList(apiParams, (res) => {
                that.mentList = res.datas
            })
        },
        initGeoJson() {
            var that = this;
            let gjson = "shuichang.json";
            QuarkGIS.Math.setRandomNumberSeed(0); //设置随机数种子
            QuarkGIS.GeoJsonDataSource.load(gjson, {
                clampToGround: true,
            }).then(function (dataSource) {
                viewer.dataSources.add(dataSource);
                viewer.flyTo(dataSource);
                var entities = dataSource.entities.values;
                for (var i = 0; i < entities.length; i++) {
                    var m = entities[i];
                    m.polyline.material = QuarkGIS.Color.CYAN;
                    // if(i == 1){
                    // 	m.polyline.material = QuarkGIS.Color.RED;
                    // }
                    // m.polyline.material = new QuarkGIS.Color(255,255,255, 1)
                }
            });
        },
        getCommonPointList() {
            var that = this;
            var pointList = [];
            for (var i = 0; i < that.mentList.length; i++) {
                if (that.showPointType == that.mentList[i].third_ment_type) {
                    pointList.push(that.mentList[i]);
                }
            }
            return pointList;
        },
        initPoint() {
            var that = this;
            var check_billboards = viewer.scene.primitives.get(1);
            var billboards = check_billboards
                ? check_billboards
                : viewer.scene.primitives.add(new QuarkGIS.BillboardCollection());
            billboards.removeAll();
            var pointList = that.getCommonPointList();

            Popup.setPopupVisible(false); // 隐藏信息框
            if (pointList.length > 0) {
                for (let i = 0; i < pointList.length; i++) {
                    var lon = Number(pointList[i].third_ment_longitude);
                    var lat = Number(pointList[i].third_ment_latitude);
                    var image = require("../assets/images/marker_" +
                        that.showPointType +
                        "_" +
                        pointList[i].third_ment_run_status +
                        ".png");
                    billboards.add({
                        id: "marker_" + parseInt(i),
                        position: new QuarkGIS.Cartesian3.fromDegrees(lon, lat),
                        image: image,
                    });
                }
            }
        },
        changeShowPointType(e) {
            var that = this;
            that.showPointType = e;
            that.initPoint();
        },
        //初始化百度地图
        initBaiduConfig() {
            let apiParams = {};
            new ThirdMent(this).getBaiduConfig(apiParams, (res) => {
                this.geoJsonUrl = res.datas.road_map_path;
                this.BMap = new BMapGL.Map("map");
                let point = new BMapGL.Point(res.datas.coordinate_long, res.datas.coordinate_lat);
                this.BMap.setMapStyleV2({
                    styleId: '09e9a4af58e18b05848445b3fe2fe941'
                });
                this.BMap.centerAndZoom(point, 11);
                this.BMap.enableScrollWheelZoom();
                this.getCoordinateList();
            })
        },
        getCoordinateList() {
            let xhr = new XMLHttpRequest();
            xhr.open('GET', this.geoJsonUrl, true);
            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    // 处理文件内容
                    let data = JSON.parse(xhr.responseText);

                    let lineLayer = new BMapGL.LineLayer({
                        enablePicked: true,
                        autoSelect: true,
                        pickWidth: 30,
                        pickHeight: 30,
                        selectedColor: '#8dfaf7', // 选中项颜色
                        style: { // 配置样式
                            // borderMask: false,
                            strokeWeight: 5,
                            strokeStyle: 'solid',
                            strokeColor: ['case', ['boolean', ['feature-state', 'picked'], false], '#8dfaf7', ['match', ['get', 'name'], 'demo1', '#ce4848', 'demo2', '#8dfaf7', 'demo3', 'blue', '#8dfaf7']],
                        }
                    });

                    lineLayer.setData(data);
                    this.BMap.addNormalLayer(lineLayer);
                }
            };
            xhr.send();

            let apiParams = {};
            new ThirdMent(this).getCoordinateList(apiParams, (res) => {
                res.datas.forEach(item => {
                    let point = new BMapGL.Point(item.map_long, item.map_lat);
                    let label = new BMapGL.Label(item.map_name, {       // 创建文本标注
                        offset: new BMapGL.Size(15, -23)           // 设置标注的偏移量
                    })
                    let icon = new BMapGL.Icon(Icon, new BMapGL.Size(50, 50), {anchor: new BMapGL.Size(25, 35)});
                    let marker = new BMapGL.Marker(point, {icon: icon})
                    this.BMap.addOverlay(marker);
                    label.setStyle({                              // 设置label的样式
                        color: '#5384EA',
                        fontSize: '14px',
                        fontWeight: 'bold',
                        background: 'transparent',
                        border: 'none',
                    })
                    marker.setTitle(item.map_name);
                    marker.setLabel(label);
                })
            });
        },
        //初始化地图
        initMap() {
            let apiParams = {};
            new ThirdMent(this).getBaiduConfig(apiParams, (res) => {
                this.geoJsonUrl = res.datas.road_map_path;
                // BM.Config.HTTP_URL = 'http://www.bigemap.com:9000';
                // BM.Config.HTTPS_URL = 'https://hubeishuiwu.hbzlwl.cn:3000';
                // BM.accessToken = 'pk.eyJ1IjoiY3VzX2NmcnBsMGUwIiwiYSI6IjVvODdzbXA3em43cnUzeXVmbDgwM2R0dTMifQ.KMObliAIvEgvKmk2XkXENQ';
                // let map = BM.map('map', 'bigemap.zhongkexingtu', {
                //     // res.datas.coordinate_lat, res.datas.coordinate_long
                //     center: [30, 104],
                //     zoom: 3,
                //     zoomControl: false,
                //     attributionControl: false,
                //     preferCanvas: true,//适用于数据量大时 地图反应速度加快
                // });
                BM.Config.HTTPS_URL = 'https://hubeishuiwu.hbzlwl.cn:3000';
                BM.accessToken = 'pk.eyJ1IjoiY3VzX2NmcnBsMGUwIiwiYSI6IjVvODdzbXA3em43cnUzeXVmbDgwM2R0dTMifQ.KMObliAIvEgvKmk2XkXENQ';
                var map = BM.map('map', 'bigemap.bczfwq0l', {
                    crs: BM.CRS.EPSG4326,
                    center: [30, 104],
                    zoom: 8,
                    zoomControl: true,
                    attributionControl: false,
                    preferCanvas: true,//适用于数据量大时地图反应速度加快
                });

                if (this.geoJsonUrl) {
                    let geo;
                    let xhr = new XMLHttpRequest();
                    let layer = new BM.CanvasMarkerLayer({
                        drawTooltip: true,
                        minZoom: 0,
                        font: '17px Helvetica Neue',
                        fillStyle: '#F00'
                    });

                    xhr.onreadystatechange = function () {
                        // 通信成功时，状态值为4
                        if (xhr.readyState === 4) {
                            if (xhr.status === 200) {
                                let dom = (new DOMParser()).parseFromString(xhr.responseText, 'text/xml');
                                let geojsonFeature = toGeoJSON.kml(dom);
                                geo = BM.geoJSON(geojsonFeature, {
                                    style: function (feature) {
                                    },
                                    pointToLayer: function (geoJsonPoint, latlng) {
                                        let marker = BM.marker(latlng)
                                        marker.bindTooltip(geoJsonPoint.properties.name, {
                                            permanent: true,
                                            className: 'my_tooltip'
                                        }).openTooltip()
                                        return marker
                                    }
                                }).addTo(map);
                                layer.addTo(map);
                                map.fitBounds(geo.getBounds());
                            } else {
                                console.error(xhr.statusText);
                            }
                        }
                    };

                    xhr.onerror = function (e) {
                        console.error(xhr.statusText);
                    };

                    // 测试 'http://localhost:8080/test.kml'
                    // 正式 this.geoJsonUrl
                    xhr.open('GET', this.geoJsonUrl, true); //方式 路径
                    xhr.send(null);
                }
            });
        },
        // 初始化鼠标点击事件
        initHandle() {
            var that = this;
            var handler = new QuarkGIS.ScreenSpaceEventHandler(viewer.scene.canvas);
            //左键点击
            handler.setInputAction(function (movement) {
                var pick = viewer.scene.pick(movement.position);
                if (QuarkGIS.defined(pick) && pick.id.indexOf("marker_") !== false) {
                    // 点击了监控探头
                    var marker_arr = pick.id.split("_");
                    var marker_index = parseInt(marker_arr[1]);
                    var pointList = that.getCommonPointList();
                    var pointInfo = pointList[marker_index];
                    pointInfo.online_status_str = pointInfo.third_ment_status == 1 ? '开' : '关';
                    pointInfo.run_status_str = pointInfo.third_ment_run_status == 1 ? '开' : '关';
                    console.log(pointInfo);
                    var scene = viewer.scene;
                    var position = QuarkGIS.Cartesian3.fromDegrees(Number(pointInfo.third_ment_longitude), Number(pointInfo.third_ment_latitude));
                    var cartesian2 = QuarkGIS.SceneTransforms.wgs84ToWindowCoordinates(scene, position)
                    console.log(cartesian2);
                    var html =
                        "<div class='popup_div'>" +
                        "<div class='popup_title'>" +
                        pointInfo.third_ment_name +
                        "</div>" +
                        "<div class='popup_content'><div class='popup_content_left'>在线状态</div><div class='popup_content_right'>" +
                        pointInfo.online_status_str +
                        "</div></div>" +
                        "<div class='popup_content'><div class='popup_content_left'>运行状态</div><div class='popup_content_right'>" +
                        pointInfo.run_status_str +
                        "</div></div>" +
                        "</div>";
                    Popup.setPopupHtml(html); // 设置弹窗内容
                    Popup.showPopupAt(cartesian2); // 显示弹窗
                    Popup.bindEventListener(cartesian2); // 绑定拖动画面的时候
                } else {
                    Popup.setPopupVisible(false);
                }
            }, QuarkGIS.ScreenSpaceEventType.LEFT_CLICK);
            //右键点击
            handler.setInputAction(function (movement) {
                //捕获椭球体，将笛卡尔二维平面坐标转为椭球体的笛卡尔三维坐标，返回球体表面的点
                var cartesian = viewer.camera.pickEllipsoid(
                    movement.position,
                    viewer.scene.globe.ellipsoid
                );
                if (cartesian) {
                    //将笛卡尔三维坐标转为地图坐标（弧度）
                    var cartographic =
                        viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian);
                    //将地图坐标（弧度）转为十进制的度数
                    var log_String = QuarkGIS.Math.toDegrees(cartographic.longitude);
                    var lat_String = QuarkGIS.Math.toDegrees(cartographic.latitude);
                    console.log(log_String, lat_String);
                }
            }, QuarkGIS.ScreenSpaceEventType.RIGHT_CLICK);

            handler.setInputAction(function (movement) {
                //捕获椭球体，将笛卡尔二维平面坐标转为椭球体的笛卡尔三维坐标，返回球体表面的点
                that.isfullScren = !that.isfullScren;
            }, QuarkGIS.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

        },
    },
};
</script>

<style lang="scss">
.home-control {
    width: 100%;
    height: 100%;
    color: #ffffff;
    position: relative;

    user-select: none;

    .btn {
        position: absolute;
        top: 10%;
        border: none;
        background-color: #237CC9;
        left: 65%;
        z-index: 100;
    }

    .my-header {
        z-index: 11;
        position: absolute;
    }

    .my-footer {
        z-index: 11;
        position: absolute;
    }

    .home-left {
        z-index: 11;
        position: absolute;
        top: 95px;
        bottom: 90px;
        width: 400px;
        left: $main-margin;
        display: flex;
        flex-direction: column;

        .situation-water-supply {
            width: 100%;
            flex: 3;
        }

        .revenue-statistics {
            width: 100%;
            flex: 5;
        }

        .production-poor {
            width: 100%;
            flex: 6;
        }
    }

    .home-right {
        z-index: 11;
        position: absolute;
        top: 95px;
        bottom: 90px;
        width: 400px;
        right: $main-margin;
        display: flex;
        flex-direction: column;

        .website-monitoring {
            width: 100%;
            flex: 1;
        }

        .water-monitoring {
            width: 100%;
            flex: 2;
        }

        .equipment-monitoring {
            width: 100%;
            flex: 3;
        }
    }

    #quarkgisContainer {
        position: absolute;
        width: 100%;
        height: 100%;
    }

    .home-bg {
        position: absolute;
        width: 100%;
        height: 100%;
        z-index: 10;
        pointer-events: none;
        box-shadow: -400px 0px 100px 50px rgba(17, 30, 47, 0.96) inset,
        400px 0px 100px 50px rgba(17, 30, 47, 0.96) inset;
    }

    .menu_box {
        position: absolute;
        left: 20px;
        top: 20px;
        background-color: rgba(0, 0, 0, 0.5);
        padding: 10px;
        border-radius: 4px;
    }

    .tipBox {
        position: relative;
        left: 200px;
        top: 200px;
        background-color: rgba(0, 0, 0, 0.5);
        padding: 10px;
        border-radius: 4px;
    }
}

.my_tooltip {
    //color: #5384EA;
    color: red;
    font-size: 16px;
    font-weight: bold;
    background: transparent;
    border: none;
}

.my_tooltip::before {
    display: none;
}
</style>
